<template>
  <div class="app-container">
    <div class="header-row">
      <span class="page-title">订单详情</span>
      <div class="actions">
        <el-button type="primary" plain icon="Printer" @click="handlePrint">打印</el-button>
        <el-button icon="Back" @click="handleBack">返回</el-button>
      </div>
    </div>

    <el-card class="section" shadow="never">
      <template #header>
        <span>订单信息</span>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单编号">{{ order.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="取餐号">{{ order.queueNum }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ formatOrderStatus(order) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ formatPayType(order) }}</el-descriptions-item>
        <el-descriptions-item label="订单总额">{{ order.orderPrice }}</el-descriptions-item>
        <el-descriptions-item label="实付价格">{{ order.realPrice }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ parseTime(order.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ parseTime(order.orderCompleteTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="配送方式">{{ formatDeliveryType(order) }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ order.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="电话">{{ order.receiverTel }}</el-descriptions-item>
        <el-descriptions-item label="配送地址">{{ order.deliveryAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ order.orderDesc }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="section" shadow="never" style="margin-top: 16px;">
      <template #header>
        <span>商品信息</span>
      </template>

             <el-table :data="goodsWithSpecs" style="width: 100%">
         <el-table-column label="#" type="index" width="60" />
         <el-table-column label="商品" min-width="220">
           <template #default="scope">
             <div class="goods">
               <el-image v-if="scope.row.goodsImage" :src="scope.row.goodsImage" fit="cover" class="goods-img" />
               <div class="goods-main">
                 <div class="goods-name">{{ scope.row.goodsName }}</div>
                 <div class="goods-desc">{{ scope.row.goodsDesc }}</div>
               </div>
             </div>
           </template>
         </el-table-column>
         <el-table-column label="单价" prop="goodsPrice" width="120" />
         <el-table-column label="数量" prop="goodsNum" width="100" />
         <el-table-column label="包装费" prop="wrapFees" width="100" />
         <el-table-column label="小计" prop="subtotal" width="120" />
         <el-table-column label="规格" min-width="200">
           <template #default="scope">
             <div class="specs">
               <el-tag v-for="(s, i) in scope.row.specs" :key="i" class="spec-tag" type="info" effect="plain">
                 {{ s.specTypesName }}
               </el-tag>
             </div>
           </template>
         </el-table-column>
       </el-table>
    </el-card>

    <!-- 售后进度区域 - 从售后页面或待处理售后页面进入时显示 -->
    <el-card v-if="isFromAfterSales || isFromTakeAfterSales" class="section" shadow="never" style="margin-top: 16px;">
      <template #header>
        <span>售后进度</span>
      </template>
      
      <el-descriptions :column="2" border v-if="afterSalesInfo">
        <el-descriptions-item label="售后类型">{{ formatAfterSalesType(afterSalesInfo.afterSalesType) }}</el-descriptions-item>
        <el-descriptions-item label="退款类型">{{ formatRefundType(afterSalesInfo.refundType) }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ parseTime(afterSalesInfo.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="退款金额">{{ afterSalesInfo.refundPrice }}</el-descriptions-item>
        <el-descriptions-item label="售后原因" :span="2">{{ afterSalesInfo.afterSalesReason }}</el-descriptions-item>
        <el-descriptions-item label="退款原因详细" :span="2">{{ afterSalesInfo.refundReasonDescription }}</el-descriptions-item>
        <el-descriptions-item label="售后进度" :span="2">{{ afterSalesInfo.dealPace || '处理中' }}</el-descriptions-item>
        <el-descriptions-item label="处理结果" :span="2">{{ afterSalesInfo.dealResult || '待处理' }}</el-descriptions-item>
      </el-descriptions>
      
      <el-empty v-else description="暂无售后信息" />
    </el-card>

    <!-- 退款商品区域 - 从售后页面或待处理售后页面进入时显示 -->
    <el-card v-if="isFromAfterSales || isFromTakeAfterSales" class="section" shadow="never" style="margin-top: 16px;">
      <template #header>
        <span>退款商品</span>
      </template>
      
             <el-table :data="refundGoodsList" style="width: 100%" v-if="refundGoodsList.length > 0">
         <el-table-column label="#" type="index" width="60" />
         <el-table-column label="商品" min-width="220">
           <template #default="scope">
             <div class="goods">
               <el-image v-if="scope.row.goodsImage" :src="scope.row.goodsImage" fit="cover" class="goods-img" />
               <div class="goods-main">
                 <div class="goods-name">{{ scope.row.goodsName }}</div>
                 <div class="goods-desc">{{ scope.row.goodsDesc || '-' }}</div>
               </div>
             </div>
           </template>
         </el-table-column>
         <el-table-column label="单价" prop="goodsPrice" width="120" />
         <el-table-column label="数量" prop="goodsNum" width="100" />
         <el-table-column label="包装费" prop="wrapFees" width="100" />
         <el-table-column label="小计" prop="subtotal" width="120" />
         <el-table-column label="规格" min-width="200">
           <template #default="scope">
             <div class="specs">
               <el-tag v-for="(s, i) in scope.row.specs" :key="i" class="spec-tag" type="info" effect="plain">
                 {{ s.specTypesName }}
               </el-tag>
             </div>
           </template>
         </el-table-column>
       </el-table>
      
      <el-empty v-else description="暂无退款商品信息" />
    </el-card>

    <!-- 售后处理操作区域 - 仅从待处理售后页面进入时显示 -->
    <el-card v-if="isFromTakeAfterSales" class="section" shadow="never" style="margin-top: 16px;">
      <template #header>
        <span>售后处理</span>
      </template>
      
      <div style="text-align: center; margin: 20px 0;">
        <el-button 
          type="success" 
          size="large" 
          @click="handleAfterSalesProcess"
          :loading="processingAfterSales"
        >
          处理售后
        </el-button>
      </div>
    </el-card>
  </div>

  <!-- 售后处理对话框 -->
  <el-dialog v-model="afterSalesDialogVisible" title="售后处理" width="500px" append-to-body>
    <el-form ref="afterSalesFormRef" :model="afterSalesForm" :rules="afterSalesRules" label-width="100px">
      <el-form-item label="订单编号">
        <span>{{ afterSalesForm.orderNo }}</span>
      </el-form-item>
      <el-form-item label="订单金额">
        <span>¥{{ afterSalesForm.orderPrice }}</span>
      </el-form-item>
      <el-form-item label="处理结果" prop="result">
        <el-radio-group v-model="afterSalesForm.result">
          <el-radio :label="1">同意退款</el-radio>
          <el-radio :label="2">拒绝退款</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="处理说明" prop="description">
        <el-input
          v-model="afterSalesForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入处理说明"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="afterSalesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAfterSales" :loading="confirmLoading">
          确认处理
        </el-button>
      </div>
    </template>
  </el-dialog>
  
</template>

<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { listOrderGoods } from '@/api/order/orderGoods'
import { listOrderGoodsSpec } from '@/api/order/orderGoodsSpec'
import { listAfterSales, updateAfterSales } from '@/api/order/afterSales'
import { listRefundGoods } from '@/api/order/refundGoods'
import { updateOrders } from '@/api/order/orders'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const order = ref({})
const goodsWithSpecs = ref([])
const isFromAfterSales = ref(false)
const isFromTakeAfterSales = ref(false)
const afterSalesInfo = ref(null)
const refundGoodsList = ref([])

// 售后处理相关
const afterSalesDialogVisible = ref(false)
const processingAfterSales = ref(false)
const confirmLoading = ref(false)
const afterSalesForm = ref({
  orderId: null,
  orderNo: '',
  orderPrice: 0,
  result: 1, // 1-同意退款 2-拒绝退款
  description: ''
})
const afterSalesRules = {
  result: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入处理说明', trigger: 'blur' }
  ]
}

function handleBack() {
  router.back()
}

function handlePrint() {
  window.print()
}

function formatPayType(row) {
  const typeMap = {1: '微信支付', 2: '支付宝', 3: '其他'}
  return typeMap[row.payType] || ''
}
function formatDeliveryType(row) {
  const typeMap = {1: '自取', 2: '配送'}
  return typeMap[row.deliveryType] || ''
}
function formatOrderStatus(row) {
  const typeMap = {1: '待支付', 2: '待发货', 3: '待配送', 4: '配送中', 5: '已完成', 6: '已取消', 7: '售后处理中'}
  return typeMap[row.orderStatus] || ''
}

function formatAfterSalesType(type) {
  const typeMap = {1: '未支付订单', 2: '已支付订单'}
  return typeMap[type] || '未知'
}

function formatRefundType(type) {
  const typeMap = {1: '全部退款', 2: '部分退款'}
  return typeMap[type] || '未知'
}

// 处理售后
function handleAfterSalesProcess() {
  afterSalesForm.value = {
    orderId: order.value.orderId,
    orderNo: order.value.orderNo,
    orderPrice: order.value.orderPrice,
    result: 1, // 默认同意退款
    description: ''
  }
  afterSalesDialogVisible.value = true
}

// 确认售后处理
async function confirmAfterSales() {
  try {
    // 验证表单
    await proxy.$refs.afterSalesFormRef.validate()
    
    confirmLoading.value = true
    
    // 1. 更新订单状态为已完成(5)并将isAfterSales改为1
    const updateOrderData = {
      orderId: afterSalesForm.value.orderId,
      orderStatus: 5,
      isAfterSales: 1
    }
    
    await updateOrders(updateOrderData)
    
    // 2. 更新售后表中的售后进度和处理结果
    if (afterSalesInfo.value) {
      const dealResult = afterSalesForm.value.result === 1 ? '已退款' : '拒绝退款'
      const updateAfterSalesData = {
        afterSalesId: afterSalesInfo.value.afterSalesId,
        dealPace: '已完成',
        dealResult: dealResult
      }
      
      await updateAfterSales(updateAfterSalesData)
    }
    
    proxy.$modal.msgSuccess('售后处理完成')
    afterSalesDialogVisible.value = false
    
    // 返回上一页
    router.back()
    
  } catch (error) {
    console.error('售后处理失败:', error)
    if (error !== 'cancel') {
      proxy.$modal.msgError('售后处理失败，请重试')
    }
  } finally {
    confirmLoading.value = false
  }
}

// 加载售后信息
async function loadAfterSalesInfo() {
  if (!order.value.orderId) return
  
  try {
    const response = await listAfterSales({ orderId: order.value.orderId })
    if (response.rows && response.rows.length > 0) {
      afterSalesInfo.value = response.rows[0]
      // 加载退款商品信息
      await loadRefundGoodsInfo()
    }
  } catch (error) {
    console.error('加载售后信息失败:', error)
  }
}

// 加载退款商品信息
async function loadRefundGoodsInfo() {
  if (!order.value.orderId) return
  
  try {
    const response = await listRefundGoods({ orderId: order.value.orderId })
    const refundGoods = response.rows || []
    
    // 为每个退款商品补充规格信息
    const enrichedRefundGoods = await Promise.all(
      refundGoods.map(async (refundGood) => {
        try {
          // 获取商品规格信息
          const specRes = await listOrderGoodsSpec({ 
            orderId: order.value.orderId, 
            goodsId: refundGood.goodsId 
          })
          const specs = Array.isArray(specRes.rows) ? specRes.rows : []
          
          // 补充规格信息
          return {
            ...refundGood,
            specs: specs
          }
        } catch (error) {
          console.error(`加载退款商品 ${refundGood.goodsId} 规格信息失败:`, error)
          return { ...refundGood, specs: [] }
        }
      })
    )
    
    refundGoodsList.value = enrichedRefundGoods
  } catch (error) {
    console.error('加载退款商品信息失败:', error)
  }
}

onMounted(async () => {
  // 判断是否从售后页面进入
  isFromAfterSales.value = route.query?.fromAfterSales === 'true'
  // 判断是否从待处理售后页面进入
  isFromTakeAfterSales.value = route.query?.fromTakeAfterSales === 'true'
  
  // 接收列表页传来的订单基础数据
  const q = route.query?.data
  if (q) {
    try {
      order.value = JSON.parse(decodeURIComponent(q))
    } catch (e) {
      order.value = {}
    }
  }

  if (!order.value.orderId) return

  // 拉取订单商品
  const goodsRes = await listOrderGoods({ orderId: order.value.orderId })
  const goods = Array.isArray(goodsRes.rows) ? goodsRes.rows : []

  // 逐个商品拉取规格（使用 (orderId, goodsId)）
  const tasks = goods.map(async g => {
    try {
      const specRes = await listOrderGoodsSpec({ orderId: order.value.orderId, goodsId: g.goodsId })
      const specs = Array.isArray(specRes.rows) ? specRes.rows : []
      return { ...g, specs }
    } catch (e) {
      return { ...g, specs: [] }
    }
  })
  goodsWithSpecs.value = await Promise.all(tasks)
  
  // 如果是从售后页面或待处理售后页面进入，加载售后相关信息
  if (isFromAfterSales.value || isFromTakeAfterSales.value) {
    await loadAfterSalesInfo()
  }
})

</script>

<style scoped>
.app-container {
  padding: 20px;
}
.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.page-title {
  font-size: 14px;
  color: #666;
}
.actions > .el-button + .el-button {
  margin-left: 8px;
}
.section :deep(.el-descriptions__label) {
  width: 100px;
}
.goods {
  display: flex;
  align-items: center;
}
.goods-img {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  margin-right: 12px;
}
.goods-name {
  font-weight: 600;
}
.goods-desc {
  font-size: 12px;
  color: #8c8c8c;
}
.specs {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.spec-tag {
  margin: 2px 0;
}
</style>